const { User, friend_request, friendList } = require("../../../models")

// 搜索用户
function searchUser(io, socket, data, callback) {
    User.findOne({ phone: data })
    .then(res => callback({ 
        status_code: 200,
        data: {
            phone: res.phone,
            nickname: res.nickname,
            headImgUrl: res.headImgUrl,
        },
    }))
    .catch(err => callback({ error: '搜索用户失败', details: err }));
}

// 发送好友请求
async function addFriend(io, socket, data, callback) {
    try {
        // 获取接收者信息
        const receiver = await User.findOne({ phone: data.receiver }).populate("applications");
        if (!receiver) {
            return callback({ status_code: 404, info: '用户不存在' });
        }
        
        // 获取发送者信息
        const sender = await User.findOne(
            { phone: data.sender}, 
            { _id: 1, nickname: 1, headImgUrl: 1, phone: 1, applications: 1 }
        );
        
        // 检查双方是否已经是好友
        const senderFriendList = await friendList.findOne({ phone: data.sender });
        const receiverFriendList = await friendList.findOne({ phone: data.receiver });
        
        // 检查发送者的好友列表中是否已经包含接收者
        if (senderFriendList && senderFriendList.friends.some(
            friend => friend.friendId && friend.friendId.toString() === receiver._id.toString()
        )) {
            return callback({ 
                status_code: 400, 
                info: `您已经添加了${receiver.nickname}为好友` 
            });
        }
        
        // 检查接收者的好友列表中是否已经包含发送者
        if (receiverFriendList && receiverFriendList.friends.some(
            friend => friend.friendId && friend.friendId.toString() === sender._id.toString()
        )) {
            return callback({ 
                status_code: 400, 
                info: `您已经添加了${receiver.nickname}为好友` 
            });
        }
        
        // 搜索接收者的申请列表，如果发现已经有发送者的申请了，说明已经发送过好友请求了
        if (receiver.applications.some(item => item.user_id && item.user_id.toString() === sender._id.toString())) {   
            return callback({ status_code: 409, info: '不要重复发送好友请求' });
        }

        // 创建好友请求
        const request = await friend_request.create({
            sender: sender._id,
            receiver: receiver._id,
            status: 0,
            time: new Date(),
            postscript: data.postscript, 
        });
        
        // 如果没有就为接收者和发送者添加好友请求
        receiver.applications.push(request._id);
        sender.applications.push(request._id);

        await sender.save();
        await receiver.save();

        // 如果对方在线还要通知它，有人要加他好友
        if (receiver.socketId) {   
            const populatedRequest = await friend_request.findById(request.id)
                .populate({ 
                    path:'sender receiver', 
                    select: { headImgUrl: 1, nickname: 1 }
                });
                
            socket.to(receiver.socketId).emit("listen_applications", populatedRequest);
        }
        
        callback({ status_code: 200, info: '好友请求已发送' });
    } catch (error) {
        console.error('发送好友请求失败:', error);
        callback({ status_code: 500, info: '发送好友请求失败', error: error.message });
    }
}

// 设置好友备注
async function setRemark(io, socket, data, callback) {
    try {
        const { friendId, remark, phone } = data;
        console.log(friendId, remark, phone);
        
        // 更新当前用户的好友列表中的备注
        await friendList.updateOne(
            { 
                phone,
                'friends.friendId': friendId 
            },
            { 
                $set: { 'friends.$.remark': remark } 
            }
        );
        
        // 获取更新后的好友列表
        const updatedFriendList = await friendList.findOne({ phone })
            .populate({ 
                path: "friends", 
                populate: [
                    { path: "friendId", select: "headImgUrl nickname phone socketId upvote DynamicList" }
                ]
            });
            
        // 返回更新成功消息和更新后的好友列表
        socket.emit('setRemarkSuccess', { 
            code: 200, 
            message: '设置备注成功',
            friends: updatedFriendList.friends
        });
    } catch (error) {
        console.error('设置备注失败:', error);
        socket.emit('setRemarkError', { code: 500, message: '设置备注失败' });
    }
};

module.exports = {
    searchUser,
    addFriend,
    setRemark
}